<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <link rel="stylesheet" href="../css/login.css">
  <title>用户注册</title>
</head>
<body>
  <div id="login_box">
    <h2>注册</h2>

    <div id="input_box">
      <input type="text" placeholder="请输入用户名" id="username">
    </div>
    <div class="input_box">
      <input type="password" placeholder="请输入密码" id="password1">
      <input type="password" placeholder="请输再次入密码" id="password2">
    </div>

    <button id="register">注册</button>
  </div>

  <script>
    const registerBtn = document.getElementById('register');

    const nameText = document.getElementById("username");
    const passwordText1 = document.getElementById('password1');
    const passwordText2 = document.getElementById('password2');

    registerBtn.addEventListener('click', () => {
      const userPattern = /^[A-z0-9]{6,20}$/;
      const passwordPattern = /^[a-zA-Z0-9]{8,15}$/;

      if (!userPattern.test(nameText.value)) {
        alert('用户名由6-20位字母、数字组成！');
        return;
      }
      if (!passwordPattern.test(passwordText1.value)) {
        alert('密码由8-15位字母、数字组成！');
        return;
      }
      if (!passwordPattern.test(passwordText2.value)) {
        alert('密码由8-15位字母、数字组成！');
        return;
      }
      
      if (nameText.value.length && passwordText1.value.length && passwordText1.value.length) {
        if (passwordText1.value === passwordText2.value) {
          axios.get('http://localhost:8080/account/accountRegister', {
            params: {
              username: nameText.value,
              password: passwordText1.value
            }
          }).then(function(res) {
            if (res.data == 'success') {
              alert('注册成功，请登录！');
              window.location.href = './login.html';
            } else {
              alert('用户名已存在，请重新输入！');
            }
          }).catch(function(err) {
            console.log(err);
          });
        } else {
          alert('两次输入的秘密不相同');
        }
      } else {
        alert('请输入用户名或密码');
      }
    })
  </script>
</body>
</html>